/**
 * Created by xw2sy on 2017-03-18.
 * 工具类和jquery组件
 */

var util={
    el:{
        success:function(title,callback){
            new PNotify({
                title: '操作提示',
                text: title,
                type: 'success',
                styling: 'bootstrap3'
            });
            if(callback){
                setTimeout(function(){
                    callback();
                },2000);
            }
        },
        successAndReload:function(title){
            this.success(title, function() {
                location.reload();
            });
        },
        successAndBack:function(title){
            this.success(title, function() {
                navManage.back(1);
            });
        },
        error:function(title,msg){
            new PNotify({
                title: '操作提示',
                text: msg||title,
                type: 'error',
                styling: 'bootstrap3'
            });
        },
        confirm:function(title,callback){
            $("#js-modal-dialog .modal-body").html(title);
            $("#js-modal-dialog").modal();
            //确认
            $("#js-modal-dialog .confirm-ok").one("click",function(){
                if(callback){
                    callback();
                    //关闭
                    $("#js-modal-dialog").click();
                }
            });
        },
        //将原页面表单数据和本页选择的数据提交回原页面
        postBack:function (selectedItems) {
            var reg=/(\w+)=([^&]+)/g;
            var params=decodeURIComponent($("#jsFormSummery").val());
            var mc;
            var hds="";
            var items={};
            //获取本页面选择的数据合并到原页面表单数据中
            for(var p in selectedItems){
                items[p]=selectedItems[p];
            }
            //取得原页面表单数据
            while(mc=reg.exec(params)){
                if(!items[mc[1]]){
                    //若和选择有相同的数据项则使用选择的
                    items[mc[1]]=mc[2];
                }
            }
            //标识为提交返回页面
            items["_isPostBack"]="1";
            //生成表单元素提交
            for(var p in items){
                hds+=util.str.fmt('<input type="hidden" name="{0}" value="{1}"/>',p,items[p]);
            }
            var backUrl=navManage.popAndGetBack();
            $('<form method="post" action="'+backUrl+'"></form>').
            append(hds).submit();
        },
        //如果表达式成立则页面跳转到指定url
        redirectIf:function (url,bool) {
            if(!!bool){
                //删除当前url导航，防止被导航回来
                navManage.pop();
                //跳转
                location.href=url;
            }
        },
        //如果提交成功能跳转到指定url
        redirectIfSubmitSuccess:function (url) {
            this.redirectIf(url,globalData.submitSuccess);
        },
        //生成树数据
        genNoDelayTree:function(options){
            //源数据数组(必须是以父节点在前的顺序的数组)
            var srcList=options.data || [];
            //根节点文本
            var rootText=options.rootText || "";
            //根节点值
            var rootValue=options.rootValue || "";
            //选中节点Id
            var selectedNodeId=options.selectedNodeId || "";
            //数据父节点名称
            var dataParentId=options.dataParentId || "parentId";
            //数据文本的属性名
            var dataTextName=options.dataTextName || "name";
            //数据值的属性名
            var dataValueName=options.dataValueName || "value";

            function newNode(n) {
                var node={};
                //生成父级节点
                node[dataTextName]=n[dataTextName];
                node[dataValueName]=n[dataValueName];
                node.state={selected:n[dataValueName]==selectedNodeId};
                node.tags=[0];
                return node;
            }

            var dataTree=[{nodes:[],tags:[0]}];
            dataTree[0][dataTextName]=rootText||"请选择";
            dataTree[0][dataValueName]=rootValue||"";
            $.each(srcList,function(i,n){
                if(n[dataParentId]==0){
                    var node=newNode(n);
                    dataTree[0].nodes.push(n);
                    dataTree[0].tags[0]=dataTree[0].nodes.length;
                }else{
                    $.each(dataTree[0].nodes,function(j,m){
                        //再循环父节点挂上子节点
                        if(n[dataParentId]==m[dataValueName]){
                            if(!m.nodes){
                                m.nodes=[];
                            }
                            m.tags[0]=m.nodes.length;
                            var node=newNode(n);
                            m.nodes.push(node);
                        }
                    });
                }
            });
            return dataTree;
        },
        //生成树数据
        genTreeData:function(options){
            //源数据数组(必须是以父节点在前的顺序的数组)
            var srcList=options.data || [];
            //根节点文本
            var rootText=options.rootText || "";
            //根节点值
            var rootValue=options.rootValue || "";
            //选中节点Id
            var selectedNodeId=options.selectedNodeId || "";
            //数据父节点名称
            var dataParentId=options.dataParentId || "parentId";
            //数据文本的属性名
            var dataTextName=options.dataTextName || "name";
            //数据值的属性名
            var dataValueName=options.dataValueName || "value";

            function newNode(n) {
                var node={};
                //生成父级节点
                node[dataTextName]=n[dataTextName];
                node[dataValueName]=n[dataValueName];
                node.state={selected:n[dataValueName]==selectedNodeId};
                node.tags=[0];
                return node;
            }

            var dataTree=[{nodes:[],tags:[0]}];
            dataTree[0][dataTextName]=rootText||"请选择";
            dataTree[0][dataValueName]=rootValue||"";
            $.each(srcList,function(i,n){
                if(n[dataParentId]==0){
                    var node=newNode(n);
                    //先存入父节点
                    dataTree[0].nodes.push(node);
                    dataTree[0].tags[0]=dataTree[0].nodes.length;
                }else{
                    $.each(dataTree[0].nodes,function(j,m){
                        //再循环父节点挂上子节点
                        if(n[dataParentId]==m[dataValueName]){
                            if(!m.nodes){
                                m.nodes=[];
                            }
                            m.tags[0]=m.nodes.length;
                            var node=newNode(n);
                            m.nodes.push(node);
                        }
                    });
                }
            });
            return dataTree;
        }
    },
    str:{
        //格式化输出fmt("{0}xxx{1}xxx",1,2)=>1xxx2xxx
        fmt:function(str,data){
            if(!str){
                return str;
            }
            //数据为数组时，转为多参数调用
            if(data instanceof Array){
                data.unshift(str);
                return arguments.callee.apply(this,data);
            }
            for(var i=1; i<arguments.length; i++){
                str=str.replace(new RegExp("\\{"+(i-1)+"\\}","gi"),arguments[i]);
            }
            return str;
        }
    },
    rootUrl:function(){
        var path="/"+webContextName+"/";
        path=path.replace(/\/+/g,"/")
        return location.protocol+"//"+location.host+path;
    },
    //获取所有请求参数
    request:{
        param:function(name){
            if(typeof name == "undefined"){
                var result = location.search.match(new RegExp("[\?\&][^\?\&]+=[^\?\&]+","g"));
                if(result == null){
                    return "";
                }
                var params={};
                var key="";
                var keyVal="";
                for(var i = 0; i < result.length; i++){
                    keyVal=result[i].split("=");
                    key=keyVal[0].substring(1);
                    params[key]=keyVal[1];
                }
                return params;
            }else{
                this.param()[name]||"";
            }
        },
        path:function(){
            return location.origin+pathname;
        },
        urlAppend:function(url,param){
            if(url){
                if(typeof param != "string"){
                    param=$.param(param);
                }
                return url+(url.indexOf("?")>0?"":"?")+"&"+param;
            }
            return url;
        },
        append:function(param){
            return this.urlAppend(location.href, param);
        },
        post:function (url,data,onSuccess,onFail) {
            var onSuccess=onSuccess||util.el.success;
            var onFail=onFail||util.el.error;
            $.post(url,data,function (r) {
                if(r && r.result){
                    onSuccess.call(r,r.data);
                }else{
                    onFail.call(r,r.data);
                }
            });
        }
    }
}

//管理前进后退
~function () {
    var mapStr="__urlMap";
    var stackStr="__urlStack";
    var urlMap=JSON.parse(sessionStorage[mapStr]||"{}");
    var urlStack=JSON.parse(sessionStorage[stackStr]||"[]");
    var currPos=0;
    var navManage={
        //将当前url入栈
        push:function (url) {
            var url=url||location.href;
            //当前位置
            currPos=urlMap[url]||0;
            if(!currPos){
                //未找到相同的url
                for(var p in urlMap){
                    var url1=p.replace(/\?.*/g,"");
                    var url2=url.replace(/\?.*/g,"");
                    if(url1==url2){
                        //找到相似的url
                        currPos=urlMap[p]||0;
                        break;
                    }
                }
            }
            //url栈里有值则不用入栈
            if(currPos){
                return;
            }
            urlStack.push(url);
            urlMap[url]=urlStack.length;
            currPos=urlStack.length;
            //存储到session中
            this.store();
        },
        //出栈当前url
        pop:function (url) {
            var url=url || location.href;
            urlStack.pop(url);
            delete urlMap[url];
            //存储到session中
            this.store();
        },
        //获取回退的url
        getBack:function (count) {
            var count=count||1;
            //定位当前位置
            for(var p in urlMap){
                if(p==location.href){
                    currPos=urlMap[p]||1;
                    break;
                }
            }
            count=count>currPos?1:count;
            //回退到的目的url
            var targetUrl=urlStack[currPos-count-1];
            return targetUrl;
        },
        //出栈并获取回退url
        popAndGetBack:function(count){
            //获取回退的url
            var targetUrl=this.getBack(count)
            //出栈当前url
            this.pop();
            return targetUrl;
        },
        //回退count次
        back:function (count) {
            //获取回退的url
            var targetUrl=this.popAndGetBack(count);
            location.href=targetUrl;
        },
        store:function () {
            //存储到session中
            sessionStorage[mapStr]=JSON.stringify(urlMap);
            sessionStorage[stackStr]=JSON.stringify(urlStack);
        },
        //清除导航栈
        clear:function () {
            sessionStorage.removeItem(mapStr);
            sessionStorage.removeItem(stackStr);
        }
    };
    window.navManage=navManage;
}();

//jquery boostrap树插件
(function($){
    var nodeHandlerCls="tree_handler";
    var closedCls="fa-plus";
    var expandedCls="fa-minus";
    var nodeTemplate='<li id="tree_node_{0}" class="list-group-item {1}"><input name="{2}" type="checkbox" value="{3}" {4} disabled="disabled"/><input name="{5}" type="checkbox" value="{6}" {7} disabled="disabled"/><a href="javascript:;" class="'+nodeHandlerCls+' fa {8}"></a><a href="#">{9}</a></li>';
    //改变一下位置，现在多选框
    var nodeTemplateDelay='<li id="tree_node_{0}" class="list-group-item"><a href="javascript:;" class="'+nodeHandlerCls+' fa {8}"></a><input name="{2}" type="checkbox" class="showInput" value="{3}" {4} /><input name="{5}" type="checkbox" value="{6}" {7} disabled="disabled"/><a href="#">{9}</a></li>';
    //节点状态
    var nodeState={
        closed:0,
        expanded:1,
        unselected:2,
        selected:3
    };
    /**
     * 生成node节点（无延迟加载，一次性生成所有节点，适合菜单类列表）
     * @param options
     * @param data
     * @param parentId
     * @param depth
     * @returns {string}
     */
    function genNodeNoDelay(options,data,parentId,depth) {
        var tree="";
        //深度已经到尽头
        var isEndDepth=(depth>=options.depth);
        $.each(data,function (i,n) {
            var value=n[options.value] || n[options.valueName];
            var text=n[options.text]  || n[options.textName];
            // var isSelected=(value!="" && options.selectedValue==value);
            var isSelected=(value!="" && n.checked);
            if(options.roleId=="1"||options.roleId==1) {
                 isSelected=true;
            }
            //有子节点
            var hasChildren=n.nodes && n.nodes.length>0;
            tree+=util.str.fmt(nodeTemplateDelay,
                //parentId+"_"+value,//id
                value,//id
                isSelected?"active":"",//是否选中
                options.valueName,//值名称
                value,//值
                isSelected?"checked":"",//是否选中
                options.textName,//文本名称
                text,//文本,
                isSelected?"checked":"",//是否选中
                isEndDepth?closedCls:expandedCls,//展开闭合图标
                text//文本
            );
            if(hasChildren){
                tree+=genNodeNoDelay(options,n.nodes,parentId+"_"+n[options.value],depth+1);
            }
        });
        if(!parentId){
            return util.str.fmt('<input type="text" name="{0}" value="{1}" {2} style="width: 0px;position: absolute;z-index: -100;"/><ul class="treeview list-group col-xs-12">{3}</ul>',
                options.valueName,options.selectedValue,options.required?"required":"",tree);
        }
        return '<li class="list-group-item sub-menu" style="display: '+(depth-1>=options.depth?'none':'block')+';"><ul class="">'+tree+'</ul></li>';
    }

    /**
     * 生成node节点
     * @param options
     * @param data
     * @param parentId
     * @param depth
     * @returns {string}
     */
    function genNode(options,data,parentId,depth) {
        var tree="";
        //深度已经到尽头
        var isEndDepth=(depth>=options.depth);
        $.each(data,function (i,n) {
            var value=n[options.value] || n[options.valueName];
            var text=n[options.text]  || n[options.textName];
            var isSelected=(value!="" && options.selectedValue==value);
            //有子节点
            var hasChildren=n.nodes && n.nodes.length>0;
            tree+=util.str.fmt(nodeTemplate,
                //parentId+"_"+value,//id
                value,//id
                isSelected?"active":"",//是否选中
                options.valueName,//值名称
                value,//值
                isSelected?"checked":"",//是否选中
                options.textName,//文本名称
                text,//文本,
                isSelected?"checked":"",//是否选中
                isEndDepth?closedCls:expandedCls,//展开闭合图标
                text//文本
            );
            if(hasChildren){
                tree+=genNode(options,n.nodes,parentId+"_"+n[options.value],depth+1);
            }
        });
        if(!parentId){
            return util.str.fmt('<input type="text" name="{0}" value="{1}" {2} style="width: 0px;position: absolute;z-index: -100;"/><ul class="treeview list-group col-xs-12">{3}</ul>',
                options.valueName,options.selectedValue,options.required?"required":"",tree);
        }
        return '<li class="list-group-item sub-menu" style="display: '+(depth-1>=options.depth?'none':'block')+';"><ul class="">'+tree+'</ul></li>';
    }

    /**
     * 设置节点状态
     * @param state
     */
    function setNodeState(state) {
        if(
            state==nodeState.closed ||
            state==nodeState.expanded
        ){
            //关闭状态
            var handler=$("."+nodeHandlerCls,this).
            removeClass(closedCls).
            removeClass(expandedCls);
            handler.addClass(state==nodeState.closed?closedCls:expandedCls);
        }
    }

    /**
     * 展开子节点
     */
    function expandSubNodes(options) {
        var next=$(this).next();
        //显示为展开的状态
        setNodeState.call(this,nodeState.expanded);
        //有子节点，展开子节点
        if(next.length>0 && next.is(".sub-menu")){
            next.show();
            $(this).data("isExpanded",true);
        }else{
            //异步加载数据
            if(options.remote){
                var that=$(this).append('<i class="tree_loading fa fa-refresh fa-spin"></i>');
                var parentId=$("input:first",this).val();
                $.getJSON(util.str.fmt(options.remote,parentId),function (r) {
                    if(r && r.result&&r.data&&r.data.length>0){
                        var tree=genNode(options,r.data,parentId,1);
                        that.after(tree);
                    }
                    $("i",that).remove();
                });
            }
        }
    }

    /**
     * 关闭子节点
     */
    function  closeSubNodes() {
        var next=$(this).next();
        //显示为关闭的状态
        setNodeState.call(this,nodeState.closed);
        //有子节点，关闭子节点
        if(next.length>0 && next.is(".sub-menu")){
            next.hide();
            $(this).data("isExpanded",false);
        }
    }

    /**
     * 展开或关闭子节点
     */
    function expandOrCloseSubNodes(options) {
        if($(this).data("isExpanded")==true||typeof($(this).data("isExpanded"))=="undefined"){
            closeSubNodes.call(this);
        }else{
            expandSubNodes.call(this,options);
        }
    }

    /**
     * 绑定节点事件
     */
    function  bindNodeEvent(options) {
        $that=$(this);
        //选中节点
        $(this).on("click",".list-group-item",function () {
            if($(this).is(".sub-menu")){
                return false;
            }
            var selectedNodeId=$that.data("selectedNodeId") || "tree_node_"+options.selectedValue;
            var thisId=$(this).attr("id");
            $("#"+selectedNodeId).removeClass("active");
            $(this).addClass("active");
            $that.data("selectedNodeId",thisId);

            var rootNode=$(this).closest(".treeview");
            $(":checkbox",rootNode).prop("checked",false);
            //选中或取消选中当前节点值
            var currVal=$(":checkbox",this).prop("checked",true).val();
            //设置/取消 树当前选中值
            rootNode.prev().val(currVal);

            //在选中状态下继续点击则进行展开和闭合操作
            if(!selectedNodeId || selectedNodeId==thisId){
                //展开或闭合节点
                expandOrCloseSubNodes.call(this,options);
            }
            return false;
        });

        //展开、收起按钮
        $(this).on("click",".tree_handler",function () {
            expandOrCloseSubNodes.call($(this).parent()[0],options);
            return false;
        });

        //checkbox事件
        $(this).on("click","input[type='checkbox'].showInput",function() {
            if(options.roleId=="1"){
                alert("中心管理员禁止编辑自己权限");
                return false;
            }
            //刷新本节点的勾选
            var boo = $(this)[0].checked;
            var fatherLi = $(this).parent("li.list-group-item");
            //将勾选node的子node同步(dom上是并列的兄弟节点)
            $(this).parent("li.list-group-item").next(".sub-menu").find(".showInput").each(function(i,n) {
                n.checked=boo;
            });
            //判断是否需要勾选父节点（祖先节点就算了）
            if(fatherLi.attr("id").substring(10)!=0){
                if(boo){
                    fatherLi.siblings("li").children(".showInput").each(function(i,n) {
                        if(!n.checked){
                            boo = false;
                            return false;
                        }
                    });
                }
                if(!boo){ $(".treeview").children("li:first").find(".showInput")[0].checked = boo;}
                fatherLi.parents("li.sub-menu").prev("li").children(".showInput")[0].checked = boo;
            }
        })
    }

    $.fn.extend({
        treenomal:function(options){
            var defaults = {text:'text', value: "value",textName:"textName",valueName:"valueName",depth:1,selectedValue:"",required:false,mutiple:false,remote:"",roleId:"roleId",data:[]};
            options = $.extend({},defaults, options);
            return $(this).each(function(){
                var tree=genNodeNoDelay(options,options.data,"",1);
                $(this).append(tree);
                bindNodeEvent.call(this,options);
            });
        }
    });

    $.fn.extend({
        treeview:function(options){
            var defaults = {text:'text', value: "value",textName:"textName",valueName:"valueName",depth:1,selectedValue:"",required:false,mutiple:false,remote:"",data:[]};
            options = $.extend({},defaults, options);
            return $(this).each(function(){
                var tree=genNode(options,options.data,"",1);
                $(this).append(tree);
                bindNodeEvent.call(this,options);
            });
        }
    });

})(window.jQuery);


//jquery boostrap 模态框插件
(function($){
    var dialogTemplate=
        '<div class="juqery-plugin-dialog modal fade" tabindex="-1">'+
        '<div class="modal-dialog modal-sm">'+
        '<div class="modal-content">'+
        '<div class="modal-header">'+
        '   <h4 class="modal-title"></h4>'+
        '</div>'+
        '<div class="modal-body"></div>'+
        '<div class="modal-footer">'+
        '</div></div></div></div>';

    function closeDialog() {
        $(".modal-backdrop").remove();
        $(this).closest(".juqery-plugin-dialog").remove();
    }

    $.fn.extend({
        dialog:function(options){
            $(".juqery-plugin-dialog").remove();
            var defaults = {title:"提示",content:"",ok:{text:"确定"},cancel:null};
            options = $.extend({},defaults, options);
            return $(this).each(function(){
                var dialog=$(dialogTemplate);
                $(".modal-title",dialog).html(options.title);
                $(".modal-body",dialog).append($(this).html());
                if(options.cancel){
                    $('<button type="button" class="btn btn-default">'+options.cancel.text+'</button>')
                        .click(function () {
                            closeDialog.call(this);
                        }).appendTo($(".modal-footer",dialog));
                }
                if(options.ok){
                    $('<button type="button" class="btn btn-primary">'+options.ok.text+'</button>')
                        .click(function () {
                            closeDialog.call(this);
                        }).appendTo($(".modal-footer",dialog));
                }
                dialog.modal();
            });
        }
    });

})(window.jQuery);
